<link rel="stylesheet" href="nepadmin/lay/extends/dtree/dtree.css">
<link rel="stylesheet" href="nepadmin/lay/extends/dtree/font/iconfont.css">
<div class="layui-fluid" lay-title="表单组合">
    <div class="layui-card">
        <div class="layui-card-body" style="padding: 15px;">
            <form class="layui-form" action="" lay-filter="form-group">
                <div class="layui-form-item">
                    <label class="layui-form-label">分类</label>
                    <div class="layui-input-block">
                        <input type="hidden" name="categoryIds">
                        <input type="text" name="categoryNames" lay-verify="required" autocomplete="off" placeholder="请选择分类" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">标题</label>
                    <div class="layui-input-block">
                        <input type="text" name="title" lay-verify="required" autocomplete="off" placeholder="请输入标题" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">作者</label>
                    <div class="layui-input-block">
                        <input type="text" name="author" lay-verify="required" autocomplete="off" placeholder="请输入作者" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">关键字</label>
                    <div class="layui-input-block" >
                        <div class="tags" id="tags">
                            <input type="text" id="keywords" name="keywords" autocomplete="off" placeholder="请输入关键字" class="layui-input">
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">封面图</label>
                    <div class="layui-input-inline">
                        <div class="layui-upload-list" style="margin:0">
                            <img src="/nepadmin/images/profile.jpg" style="width: 120px;height: 120px" id="srcimgurl" class="layui-upload-img">
                            <input type="hidden" id="image" name="image">
                        </div>
                    </div>
                    <div class="layui-input-inline layui-btn-container" style="width: auto;">
                        <button class="layui-btn layui-btn-primary" type="button" id="editimg">修改图片</button >
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">有效</label>
                    <div class="layui-input-block">
                        <input type="radio" name="type" value="1" title="普通" checked="">
                        <input type="radio" name="type" value="2" title="热门">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">内容</label>
                    <div class="layui-input-block" id="editor">

                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit="" lay-filter="form-group-submit">立即提交</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    layui.use(['jquery', 'api','admin', 'form','upload', 'selectM','laydate', 'layer', 'dtree','conf','wangEditor','inputTags'], function () {
        var $ = layui.jquery
            , layer = layui.layer
            , api = layui.api
            , laydate = layui.laydate
            , form = layui.form
            , admin = layui.admin
            , conf = layui.conf
            , selectM = layui.selectM
            , dtree = layui.dtree
            , upload = layui.upload
            , inputTags = layui.inputTags;
        var cmsArticle = {};
        var id = POPUP_DATA.id;
        var table = POPUP_DATA.table;
        form.render(null, 'form-group');
        laydate.render({
            elem: '#form-group-date'
        });
        // 编辑器
        var E =  layui.wangEditor;
        var editor = new E("#editor");
        editor.customConfig.uploadImgParams = {
            token: admin.loginToken
        };
        editor.customConfig.uploadFileName = 'myfiles';
        editor.customConfig.uploadImgServer = conf.requestUrl + 'fileUpload';
        editor.create();

        // 上传图片处理
        var uploadInst = upload.render({
            elem: '#editimg'
            ,url: '/fileUpload'
            ,field: 'myfiles'
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#srcimgurl').attr('src', result); //图片链接（base64）
                });
            }
            ,done: function(res){
                //如果上传失败
                if(res.code != '0'){
                    return layer.msg('上传失败');
                }
                //上传成功,作为上传参数
                console.log(res.data);
                $("#image").val(res.data[0]);
            }
            /*,error: function(){
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            }*/
        });

        // 初始化
        admin.get({
            type: 'get',
            url: '/cmsArticle/info?id='+id,
            dataType: 'json',
            success: function(data){
                cmsArticle = data.cmsArticle;
                if(cmsArticle){
                    form.val("form-group", {
                        "author": cmsArticle.author // "name": "value"
                        ,"title": cmsArticle.title
                        ,"categoryIds": cmsArticle.categoryIds
                        ,"categoryNames": cmsArticle.categoryNames
                        ,"image": cmsArticle.image
                        ,"type": cmsArticle.type
                    });
                    $("#srcimgurl").attr("src",cmsArticle.image);
                    editor.txt.html(cmsArticle.content);
                    // 标签
                    inputTags.render({
                        elem:'#keywords',
                        content: cmsArticle.keywords.split(","),
                        aldaBtn: true,
                        done: function(value){
                            console.log(value)
                        }
                    })
                } else {
                    // 标签
                    inputTags.render({
                        elem:'#keywords',
                        content: [],
                        aldaBtn: true,
                        done: function(value){
                            console.log(value)
                        }
                    })
                }
            }
        });


        // 弹窗
        $("input[name='categoryNames']").on("click",function(){
            layer.open({
                type: 1,
                title: "选择树",
                area: ["400px", "60%"],
                content: '<ul id="openTree1" class="dtree" data-id="0"></ul>',
                btn: ['确认'],
                success: function(layero, index){
                    var treeUrl = '/cmsCategory/queryCategoryListR?token=' + admin.loginToken;
                    var tree = dtree.render({
                        //  obj: $(layero).find("#openTree1"),    如果直接用elem加载不出来，则可以使用这个方式加载jquery的DOM
                        elem: "#openTree1",
                        method: "get",
                        dataStyle: "layuiStyle",
                        response: {statusCode: 0, rootName: "cmsCategoryList",title:"name"},
                        initLevel: 1,
                        dot: false,
                        checkbar: true,
                        skin: "zdy",  // 自定义风格
                        url: treeUrl,
                        done:function (data, obj) {
                            var categoryIds = $("input[name='categoryIds']").val();
                            dtree.chooseDataInit("openTree1", categoryIds);
                            //tree.checkAllOrNot("#openTree1");
                        }
                    });
                },
                yes: function(index, layero) {
                    var flag = true;
                    var params = dtree.getCheckbarNodesParam("openTree1"); // 获取选中值
                    var ids = [], names = [];
                    for(var key in params){
                        var param = params[key];
                        /*if (param.isLeaf) {
                        }*/
                        ids.push(param.nodeId);
                        names.push(param.context);
                    }
                    if(ids.length == 0){
                        layer.msg("请至少选择一个末级节点");
                        flag = false;
                    }
                    $("input[name='categoryIds']").val(ids.join(","));
                    $("input[name='categoryNames']").val(names.join(","));
                    if(flag){
                        layer.close(index);
                    }
                }
            });
        });

        /* 监听提交 */
        form.on('submit(form-group-submit)', function (data) {
            var field = data.field;
            var articleData={};
            articleData.title = field.title;
            articleData.author = field.author;
            articleData.categoryIds = field.categoryIds;
            articleData.image = field.image;
            articleData.type = field.type;
            // editor
            var content = editor.txt.html();
            articleData.content = content;
            // userDate.roleIds = field.tag2;
            var keywordArr=[];
            $("#tags span em").each(function(){
                var keyword = $(this).html();
                keywordArr.push(keyword);
            });
            articleData.keywords = keywordArr.join(",");
            var url = "/cmsArticle/save";
            if(id){
                url = "/cmsArticle/update?_method=PUT";
                articleData.id=id;
            }
            admin.post({
                url:url,
                contentType: "application/json",
                data:JSON.stringify(articleData),
                success:function(res){
                    if (res.code == 0){
                        // 提醒保存成功，关闭当前弹窗
                        layer.msg(res.msg);
                        layer.closeAll();
                        // 刷新
                        table.reload('list-table-cmsArticle',{
                            url:'/cmsArticle/page?token='+admin.loginToken,
                            page:{
                                curr:1
                            }
                        })
                    } else {
                        layer.msg(res.msg);
                    }
                }
            });
            return false;
        });
    });
</script>